<template>
  <v-layout type="main">

    <ul class="home-monitoring">
      <li class="cpu">
        <div class="txt">
          <p class="name">CPU</p>
          <p class="msg">
            剩余
            <span>{{ (cpuRes.limit - cpuRes.used).toFixed(1) }}</span>
            {{ cpuRes.unit }}
          </p>
        </div>
        <percentage :res="cpuRes" />
        <!-- <div class="monitoring-layer" @mouseover="monitoringOver('cpuRes')" @mouseout="monitoringOut('cpuRes')"></div> -->
      </li>
      <!-- <li class="vgpu">
        <p class="name">VGPU</p>
        <div></div>
      </li> -->
      <li class="ram">
        <div class="txt">
          <p class="name">内存</p>
          <p class="msg">
            剩余
            <span>{{ (memRes.limit - memRes.used).toFixed(1) }}</span>
            {{ memRes.unit }}
          </p>
        </div>
        <percentage :res="memRes" />
        <!-- <div class="monitoring-layer" @mouseover="monitoringOver('memRes')" @mouseout="monitoringOut('memRes')"></div> -->
      </li>

      <li class="gpu">
        <div class="txt">
          <p class="name">GPU</p>
          <p class="msg">
            剩余
            <span>{{ (gpuRes.limit - gpuRes.used).toFixed(1) }}</span>
            {{ gpuRes.unit }}
          </p>
        </div>
        <percentage :res="gpuRes" />
        <!-- <div class="monitoring-layer" @mouseover="monitoringOver('gpuRes')" @mouseout="monitoringOut('gpuRes')"></div> -->
      </li>

      <li class="ram">
        <div class="txt">
          <p class="name">硬盘</p>
          <p class="msg">
            剩余
            <span>{{ (diskRes.limit - diskRes.used).toFixed(1) }}</span>
            {{ diskRes.unit }}
          </p>
        </div>
        <percentage :res="diskRes" />
        <!-- <div class="monitoring-layer" @mouseover="monitoringOver('memRes')" @mouseout="monitoringOut('memRes')"></div> -->
      </li>
    </ul>

    <div class="radio_box">
      <el-radio-group v-model="radio" @change="changeRadio">
        <el-radio-button label="0">深度学习任务管理</el-radio-button>
        <el-radio-button label="1">强化学习任务管理</el-radio-button>
      </el-radio-group>
    </div>

    <div class="alike-lis-header">
      <div class="lis-header-left">
        <div style="font-size: 18px;">模型开发</div>
      </div>
    </div>

    <div class="table-data">
      <el-table :data="tableData">
        <el-table-column prop="name" label="名称">
          <template slot-scope="{ row }">
            <el-popover placement="right-start" width="320" trigger="hover">
              <row-data :row="row" />
              <span slot="reference">{{ row.name }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="resource.start_time" label="启动时间" />
        <!-- <el-table-column prop="update_time" label="资源组" /> -->
        <el-table-column label="运行时长">
          <template slot-scope="{ row }">
            {{ countRanTime(row.resource.start_time) }}
          </template>
        </el-table-column>
        <!--<el-table-column prop="update_time" label="环境" />-->
        <el-table-column prop="status" label="状态">
          <template slot-scope="{ row }">
            <span :class="['alick-list-status', row.status]">●{{ statusMap[row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="优先级">
          <template slot-scope="{ row }">
            <el-select v-if="row.status == 'queuing'" @change="upWiseJob(row)" v-model="row.resource.priority"
              placeholder="请选择">
              <el-option v-for="item in wiseJob" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <span v-else>{{ row.resource.priority }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作人">
          <template slot-scope="{ row }">
            {{row.create_user.username}}
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="monitoring(row, '0')" :disabled="row.status != 'running'">监控</el-button>
            <el-button type="text" @click="stop(row)">停止</el-button>
            <el-button type="text" @click="stop(row)">暂停</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="alike-lis-header">
      <div class="lis-header-left">
        <div style="font-size: 18px;">工程管理</div>
      </div>
    </div>

    <div style="margin-top: 15px;" class="table-data">
      <el-table :data="tableData1">
        <el-table-column prop="name" label="名称">
          <template slot-scope="{ row }">
            <el-popover placement="right-start" width="320" trigger="hover">
              <row-data :row="row" />
              <span slot="reference">{{ row.name }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="resource.start_time" label="启动时间" />
        <!-- <el-table-column prop="update_time" label="资源组" /> -->
        <el-table-column prop="update_time" label="运行时长">
          <template slot-scope="{ row }">
            {{ countRanTime(row.resource.start_time) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="update_time" label="环境" /> -->
        <el-table-column prop="status" label="状态">
          <template slot-scope="{ row }">
            <span :class="['alick-list-status', row.status]">●{{ statusMap[row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="优先级">
          <template slot-scope="{ row }">
            <el-select v-if="row.status == 'queuing'" @change="upWiseTask(row)" v-model="row.resource.priority"
              placeholder="请选择">
              <el-option v-for="item in wiseJob" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <span v-else>{{ row.resource.priority }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="monitoring(row, '1')" :disabled="row.status != 'running'">监控</el-button>
            <el-button type="text" @click="stop1(row)">停止</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="alike-lis-header">
      <div class="lis-header-left">
        <div style="font-size: 18px;">模型应用</div>
      </div>
    </div>

    <div style="margin-top: 15px;" class="table-data">
      <el-table :data="tableData2">
        <el-table-column prop="name" label="名称">
          <template slot-scope="{ row }">
            <el-popover placement="right-start" width="320" trigger="hover">
              <row-data :row="row" />
              <span slot="reference">{{ row.name }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="resource.start_time" label="启动时间" />
        <!-- <el-table-column prop="update_time" label="资源组" /> -->
        <el-table-column prop="update_time" label="运行时长">
          <template slot-scope="{ row }">
            {{ countRanTime(row.resource.start_time) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="update_time" label="环境" /> -->
        <el-table-column prop="status" label="状态">
          <template slot-scope="{ row }">
            <span :class="['alick-list-status', row.status]">●{{ statusMap[row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="优先级">
          <template slot-scope="{ row }">
            <el-select v-if="row.status == 'queuing'" @change="upWiseServ(row)" v-model="row.resource.priority"
              placeholder="请选择">
              <el-option v-for="item in wiseJob" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <span v-else>{{ row.resource.priority }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="monitoring(row, '2')" :disabled="row.status != 'running'">监控</el-button>
            <el-button type="text" @click="stop2(row)">停止</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

		<div class="pagination-box">
			<el-pagination
				background
				class="pagination"
				layout="total, prev, pager, next, jumper"
				:page-size="Pagedata.pageSize"
				:current-page.sync="Pagedata.pageNum"
				@current-change="handleCurrentChange"
				:total="Pagedata.total"
			>
			</el-pagination>
		</div>

    <drawer-log ref="drawerLog" :row="rowData" />
  </v-layout>
</template>

<script>
import Vue from 'vue'
import { mapActions, mapState } from "vuex";
import { getGameExperimentMonitor, stopGameExperiment } from '@/api/gameExperiment'
import { getGameTaskVersionsMonitor, stopGameTaskVersion } from '@/api/gameTask'
import { getGameSimulationMonitor, stopGameSimulation } from '@/api/gameSimulation'
import { getExperimentMonitor, stopExperiment } from '@/api/notebook'
import { getTaskVersionsMonitor, stopTaskVersion } from '@/api/task'
import { getDeploysMonitor, stopServing } from '@/api/deploy'
// import { getAllResource, networkUsageCurrent } from '@/api/dashboard'
import { getAllResource } from '@/api/dashboard'
import { getCookie, removeCookie } from '@/utils/tool'
import percentage from './../module/percentage'
import drawerLog from './../module/drawer-log'
import { updateWiseJob, wiseJob } from "../../api/dashboard";

export default {
  name: "index",
  data() {
    return {
      wiseJob: [],//排队优先级选项
      showThisActive: 0,
      tableData: [],
      tableData1: [],
      tableData2: [],
      rowData: [],
      cpuRes: {},
      diskRes: {},
      memRes: {},
      gpuRes: {},
			Pagedata: {
				pageNum: 1,
				pageSize: 12,
				total: 0,
				name: "",
			},
      statusMap: {
        init: '未运行',
        stop: '停止',
        starting: '启动中',
        creating: '创建中',
        deploying: '部署中',
        running: '运行中',
        stopping: '停止中',
        fail: '失败',
        Pending: '等待中',
        queuing: '排队中',
        Failed: '失败',
        Running: '运行中',
        Succeeded: '成功',
        terminating: "停止中",
      },
      radio: "1",
    };
  },
  components: {
    percentage,
    drawerLog
  },
  computed: mapState({
		pageNum: (state) => state.menuStore.pageData.pageNum,
		searchValue: (state) => state.menuStore.searchValue,
	}),
  methods: {
    ...mapActions(["updatePageNum", "updateSearch"]),
    //修改模型开发优先级
    async upWiseJob(row) {
      let data = {
        business_id: row.id,
        priority_class: row.resource.priority,
        business_type: this.radio ? 'experiment' : 'gameExperiment'
      }
      let res = await updateWiseJob(data)
      if (res.data) {
        this.$message.success("修改优先级成功")
      }
    },
    //修改模型训练优先级
    async upWiseTask(row) {
      let data = {
        business_id: row.id,
        priority_class: row.resource.priority,
        business_type: this.radio ? 'task' : 'gameTaskVersion'
      }
      let res = await updateWiseJob(data)
      if (res.data) {
        this.$message.success("修改优先级成功")
      }
    },
    //修改模型部署优先级
    async upWiseServ(row) {
      let data = {
        business_id: row.id,
        priority_class: row.resource.priority,
        business_type: this.radio ? 'serving' : 'gameServing'
      }
      let res = await updateWiseJob(data)
      if (res.data) {
        this.$message.success("修改优先级成功")
      }
    },
    async getWiseJobOP() {
      let res = await wiseJob();
      this.wiseJob = res.data
    },
    changeRadio(k) {
      console.log(k)
      this.$isReinforce = (k == 1) ? true : false;// k==1 强化，否则深度
      this.getData()
    },
    countRanTime(time) {
      let convert = t => {
        let millisecond = new Date() - new Date(t)
        let hour = millisecond / 1000 / 60 / 60 >= 1 ? `${parseInt(millisecond / 1000 / 60 / 60)}小时` : ''
        let minute = millisecond / 1000 / 60 % 60 >= 1 ? `${parseInt(millisecond / 1000 / 60 % 60)}分钟` : ''
        return `${hour}${minute}`
      }
      return time ? convert(time) : ''
    },
    applyResource() {

    },
    async getCakeData() {
      let resCpu = await getAllResource({ resourceType: "cpu" });
      let resMem = await getAllResource({ resourceType: "mem" });
      let resGpu = await getAllResource({ resourceType: "gpu" });
      let resDisk = await getAllResource({ resourceType: "disk" });
      this.cpuRes = resCpu.data
      resCpu.data.color = "#F0CB55"
      resCpu.data.underpainting = "rgba(35, 35, 37, .75)"

      this.memRes = resMem.data
      resMem.data.color = "#439566"
      resMem.data.underpainting = "rgba(35, 35, 37, .75)"

      this.gpuRes = resGpu.data
      this.gpuRes = resGpu.data
      resGpu.data.color = "#36B4DA"
      resGpu.data.underpainting = "rgba(35, 35, 37, .75)"

      this.diskRes = resDisk.data
      resDisk.data.color = "#2E79F6";
      resDisk.data.underpainting = "rgba(35, 35, 37, .5)"
    },

    async getExperiment() {
      let res = null
      if (this.$isReinforce) {
        res = await getGameExperimentMonitor({ all: true, ...this.Pagedata })
      } else {
        res = await getExperimentMonitor({ all: true, ...this.Pagedata })
      }
      this.tableData = res.data.list
      this.Pagedata.total = res.data.total
    },
    async getTaskVersions() {
      let res = null
      if (this.$isReinforce) {
        res = await getGameTaskVersionsMonitor({ type: 1, all: true, ...this.Pagedata })
      } else {
        res = await getTaskVersionsMonitor({ type: 1, all: true, ...this.Pagedata })
      }
      this.tableData1 = res.data.list
      this.Pagedata.total = res.data.total
    },
    async getDeploys() {
      let res = null;
      if (this.$isReinforce) {
        res = await getGameTaskVersionsMonitor({ type: 2, all: true, ...this.Pagedata })
      } else {
        res = await getDeploysMonitor({ type: 2, all: true, ...this.Pagedata })
      }
      this.tableData2 = res.data.list
      this.Pagedata.total = res.data.total
    },
    async getSimulationTask() {
      let res = await getGameSimulationMonitor({ type: 1, all: true, ...this.Pagedata })
      this.tableData = res.data.list
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].name = this.tableData[i].deploy_name
      }
      this.Pagedata.total = res.data.total
    },
    getData() {
      this.getExperiment()
      this.getTaskVersions()
      this.getDeploys()
      this.getCakeData()
    },
    monitoringOver(type) {
      let thisType = { ...this[type] }
      thisType.tempColor = thisType.color
      thisType.tempUnderpainting = thisType.underpainting
      thisType.color = '#FFF'
      thisType.underpainting = 'rgba(255, 255, 255, .2)'
      this[type] = {}
      setTimeout(() => {
        this[type] = thisType
      })
    },
    monitoringOut(type) {
      let thisType = { ...this[type] }
      thisType.color = thisType.tempColor
      thisType.underpainting = thisType.tempUnderpainting
      this[type] = {}
      setTimeout(() => {
        this[type] = thisType
      })
    },
    monitoring(row, active) {
      console.log(row, active)
      this.rowData = row
      this.rowData.active = active
      this.$refs.drawerLog.shwoDrawer = true
    },
    async stopold({ id }) {
      //console.log(id)
      if (this.showThisActive == 0) {
        if (this.$isReinforce) {
          await stopGameExperiment({ id })
        } else {
          await stopExperiment({ id })
        }
      }
      if (this.showThisActive == 1) {
        if (this.$isReinforce) {
          await stopGameTaskVersion({ id })
        } else {
          await stopTaskVersion({ id })
        }
      }
      if (this.showThisActive == 2) {
        if (this.$isReinforce) {
          await stopGameTaskVersion({ id })
        } else {
          await stopServing(id)
        }
      }
      if (this.showThisActive == 3) {
        await stopGameSimulation(id)
      }
      this.getData()
    },
    checkActicve(i) {
      this.showThisActive = i
      this.Pagedata.current = 1
      this.getData()
    },
    handleCurrentChange(val) {
      console.log('val',val)
      this.Pagedata.pageNum = val;
      this.updatePageNum(val);
      this.getData()
    },
    async stop({ id }) {
      //console.log(id)
      if (this.$isReinforce) {
        await stopGameExperiment({ id })
      } else {
        await stopExperiment({ id })
      }
      this.getData()
    },
    async stop1({ id }) {
      if (this.$isReinforce) {
        await stopGameTaskVersion({ id })
      } else {
        await stopTaskVersion({ id })
      }
      this.getData()
    },
    async stop2({ id }) {
      if (this.$isReinforce) {
        await stopGameTaskVersion({ id })
      } else {
        await stopServing(id)
      }
      this.getData()
    },
  },
  created() {
    this.getWiseJobOP()
    this.Pagedata = { ...this.Pagedata, pageNum: this.pageNum, name: this.searchValue };
		this.getData();
  },
  watch: {},
  async beforeCreate() {
    //console.log(decodeURIComponent(getCookie('login_ticket')))
    if (decodeURIComponent(getCookie('console_login_ticket')) == '') {
      this.$router.push({
        path: '/login'
      })
    } else {
      var info = await this.$myInfo(this)
      //console.log("info:",info)
      if (info != null && info.roles.length > 0) {
        if (info.id != 1) {//不是admin用户,不可以登录后台管理系统
          removeCookie('console_login_ticket')
          removeCookie('console_refresh_token')
          this.$message({
            type: 'error',
            message: '没有权限后台管理系统!'
          });
          this.$router.push({
            path: '/login'
          })
        }
      }
    }

    return
  },
  async mounted() {
    //
    if (!this.$isFirstPage) {
      Vue.prototype.$isFirstPage = true;
    }
    //
    this.getData()
    this.$EventBus.$on('experiment', () => {
      if (this.showThisActive == 0) this.getData()
    })
    this.$EventBus.$on('train', () => {
      if (this.showThisActive == 1 || this.showThisActive == 2) this.getData()
    })
    this.$EventBus.$on('serving', () => {
      if (this.showThisActive == 2) this.getData()
    })
  },
  destroyed() {
    this.$EventBus.$off('experiment')
    this.$EventBus.$off('train')
    this.$EventBus.$off('serving')
  },
};
</script>
<style lang="less" scoped>
.table-data {
  margin-bottom: 20px;
  background: #FFF;
  border-radius: 0 10px 10px 10px;
}

.home-monitoring {
  display: flex;
  width: 100%;
  margin-bottom: 20px;

  li {
    flex: 1;
    margin: 0 8px;
    height: 260px;
    background: #FFF;
    border-radius: 10px;
    cursor: pointer;
    transition: all .3s;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top: 30px;
    box-sizing: border-box;

    &:first-child {
      margin-left: 0;
    }

    &:last-child {
      margin-right: 0;
    }

    .monitoring-layer {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 2;
    }

    .txt {
      position: absolute;
      top: 20px;
      left: 25px;
      color: #A4ADCD;

      .name {
        font-size: 18px;
      }

      .msg {
        font-size: 14px;
        margin-top: 15px;

        span {
          font-size: 16px;
        }
      }
    }

    &:hover {
      background: #2A2E46 !important;
    }
  }

  .cpu {
    span {
      color: #F0CB55;
    }
  }

  .vgpu {
    span {
      color: #439566;
    }
  }

  .ram {
    span {
      color: #2E79F6;
    }
  }

  .gpu {
    span {
      color: #36B4DA;
    }
  }
}
</style>
